import { escape } from "lodash-es";
import { computed, defineComponent } from "vue";
import { safeHTML } from "@/utils/html-secure";
import { highLightProps } from "./highlight-types";

export default defineComponent({
  name: "TitanHighlight",
  props: highLightProps,
  setup(props) {
    const replaceContent = computed<string>(() => {
      return escape(props.content);
    });

    const getRegByPhone = (s: string) => {
      return s
        .split("")
        .map((i) => {
          if (i === "-") {
            return i;
          } else {
            return `(${i}-?)`;
          }
        })
        .join("");
    };

    const changeHighLightKeywords = (key: string | string[]) => {
      let t = "";
      let arr: string[] = [];
      if (typeof key === "string" && key) {
        // 关键字为单个字符串时
        t = escape(key);
        if (props.type === "phone") {
          t = [`(${getRegByPhone(key)})`, t.replaceAll("-", "")].join("|");
        }
      } else if (key instanceof Array && key.length) {
        // 关键字为多个字符串组成的数组时
        arr = key.reduce((total: string[], item: string) => {
          item && total.push(item);
          if (props.type === "phone") {
            total.push(`(${getRegByPhone(item)})`);
          }
          return total;
        }, []);
        t = arr.join("|");
      }
      const color = props.color;
      return replaceContent.value.replaceAll(new RegExp(t, "giu"), (match) => {
        return `<span style="color: ${color}">${match}</span>`;
      });
    };

    const highlightContent = computed(() => changeHighLightKeywords(props.keyword));

    return () => {
      return <span v-html={safeHTML(highlightContent.value || replaceContent.value)}></span>;
    };
  },
});
